package main

import (
	"fmt"
	"jvmgo/ch03/classfile"
	"jvmgo/ch03/classpath"
)

/**
	虚拟机主入口
 */
func main() {
	cmd := parseCmd()
	startJVM(cmd)
}

/**
	开启jvm虚拟机
 */
func startJVM(cmd *Cmd) {
	cp := classpath.Parse(cmd.cpOption)
	cf := loadClass(cmd.class, cp)
	printClassInfo(cf, cmd)
}

/**
	加载class文件
 */
func loadClass(className string, cp *classpath.Classpath) *classfile.ClassFile {
	classDataByte, _, err := cp.ReadClass(className)
	if err != nil {
		panic(err)
	}
	cf, err := classfile.Parse(classDataByte)
	if err != nil {
		panic(err)
	}
	return cf
}

/**
	打印class文件信息
 */
func printClassInfo(cf *classfile.ClassFile, cmd *Cmd) {
	fmt.Printf("\n")
	fmt.Printf("className: %v\n", cmd.class)
	fmt.Printf("version: %v.%v\n", cf.MajorVersion(), cf.MinorVersion())
	fmt.Printf("constants count: %v\n", len(cf.ConstantPool()))
	fmt.Printf("access flags: 0x%x\n", cf.AccessFlags())
	fmt.Printf("this class: %v\n", cf.ClassName())
	fmt.Printf("super class: %v\n", cf.SuperClassName())
	fmt.Printf("interfaces: %v\n", cf.InterfaceNames())
	fmt.Printf("fields count: %v\n", len(cf.Fields()))
	for _, f := range cf.Fields() {
		fmt.Printf(" %s\n", f.Name())
	}
	fmt.Printf("methods count: %v\n", len(cf.Methods()))
	for _, m := range cf.Methods() {
		fmt.Printf(" %s\n", m.Name())
	}
}